package com.example.utils;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.os.Looper;
import android.view.Gravity;
import android.widget.Toast;


public class ToastUtil extends Toast {
    private static Toast toast;

    /**
     * Construct an empty Toast object.  You must call {@link #setView} before you
     * can call {@link #show}.
     *
     * @param context The context to use.  Usually your {@link Application}
     *                or {@link Activity} object.
     */
    public ToastUtil(Context context) {
        super(context);
    }
    public static  void showToast(String string){
        if (toast!=null) {
            toast.cancel();
            toast=null;
        }
//在主线程中显示
        if("main".equals(Thread.currentThread().getName())){
            toast=Toast.makeText(UtilsContext.getAppContext(),string,Toast.LENGTH_SHORT);
            toast.setGravity(Gravity.CENTER, 0, 0);//居中弹出
            toast.show();
        }else {
            //在子线程中显示
            Looper.prepare(); // No Looper is defined So define a new one
            toast=Toast.makeText(UtilsContext.getAppContext(),string,Toast.LENGTH_SHORT);
            toast.setGravity(Gravity.CENTER, 0, 0);//居中弹出
            toast.show();
            System.out.println("ToastUtil.showToast()在子线程中，Looper.loop()后代码不执行，请慎用");
            Looper.loop();
        }
    }
    public static void dismissToast(){
        if (toast!=null) {
            toast.cancel();
            toast=null;
        }
    }
}

